package fileshare.fileprocessing;
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;

import fileshare.network.peerProcess;
public class log
{
public static boolean delete1=false;
public static boolean delete2=false;
	public static synchronized void  write2log(String content) throws IOException{      
		
		 File file=new File("LOG_PEER_"+peerProcess.str_peerid+".log");  
		 if(file.exists()&&!delete1) 
		 { file.delete();delete1=true;}
		 if(!file.exists())      
		 file.createNewFile();      
		 FileOutputStream out=new FileOutputStream(file,true);      
		   
			 
			  Date currentTime = new Date();    
			  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
			  String dateString = formatter.format(currentTime); 
			  content=peerProcess.self_index+content;
			  content=dateString+" "+content+"\n";
		 StringBuffer sb=new StringBuffer(); 
		
		 sb.append(content);      
		 out.write(sb.toString().getBytes());      
		      
		 out.close();      
		 }     
	public static synchronized void  write3log(String content) throws IOException{      
		
		 File file=new File("DEBUG_"+peerProcess.str_peerid+".log");     
		 if(file.exists()&&!delete2) 
		 { file.delete();
		 delete2=true;
			}
		 if(!file.exists())      
		 file.createNewFile();      
		 FileOutputStream out=new FileOutputStream(file,true);      
		   
			 
			  Date currentTime = new Date();    
			  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
			  String dateString = formatter.format(currentTime); 
			  content=peerProcess.self_index+content;
			  content=dateString+" "+content+"\n";
		 StringBuffer sb=new StringBuffer(); 
		
		 sb.append(content);      
		 out.write(sb.toString().getBytes());      
		      
		 out.close();      
		 } 
	public static void getExceptionTrace(Throwable e) {
		
	      
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        try{
        write2log(sw.toString());
        }catch(Exception f){f.printStackTrace();}

}
	public static void writelog(String content)
	{
		System.out.println(content);
		try{
		log.write2log(content);
		}catch(Exception e){e.printStackTrace();log.getExceptionTrace(e);}
	}
}
